package com.njqy.ticket.util;

import com.njqy.ticket.common.Constants;
import io.jsonwebtoken.*;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    //根据负载生成jwt token
    private static String createToken(Map<String, Object> claims) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 300);
        //jjwt构建jwt builder
        //设置信息，过期时间，signnature
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(instance.getTime())
                .signWith(SignatureAlgorithm.HS512, Constants.JWT_SECRET)
                .compact();
    }

    public static String createToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("subject", userDetails.getUsername());
        claims.put("created", CommonUtil.getTime());
        return createToken(claims);
    }

    //根据token获取用户名
    public static String getUsernameFromToken(String token) {
        String username = "";
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    //从token中获取荷载
    public static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(Constants.JWT_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {

        }
        return claims;
    }

}
